package com.duoduo.common.util.myhelper;


import com.duoduo.common.api.exception.CreateKeyException;
import com.duoduo.common.api.help.DateInnerUtil;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class SpringElUtil {
	
    /**
     * 解析springEl表达式
     * @param args 目标方法参数
     * @param paramNames 目标方法参数名
     * @param keyMember 表达式
     * @return
     */
    public static Object getCacheKey(Object[] args, String [] paramNames, String keyMember) throws CreateKeyException {
    	try{
	    	//创建SpringEL表达式转换器
	        ExpressionParser parser = new SpelExpressionParser();
	        //Spring
	        EvaluationContext context = new StandardEvaluationContext();
	        for(int i=0; i<args.length; i++){
	            context.setVariable(paramNames[i], args[i]);
	        }
	        //组装Key
	        return getValue(parser, context, keyMember);
    	} catch (Exception e){
        	throw new CreateKeyException("(createKey) get key from spring el error: ", e);
        }
    }

    /**
     * 获取值
     * @param parser
     * @param context
     * @param keyMember
     * @return
     */
    private static Object getValue(ExpressionParser parser, EvaluationContext context, String keyMember) throws CreateKeyException {
        try{
            Expression expression = parser.parseExpression(keyMember);
            Object value = expression.getValue(context);
            if(null == value){
                return null;
            }
            //如果值类型为java.util.Date,则进行格式转换
            if (value instanceof java.util.Date) {
                return DateInnerUtil.getStringDay((java.util.Date)value);
            } else {
                return value;
            }
        } catch (Exception e){
        	throw new CreateKeyException("(createKey) get value from spring el error: ", e);
        }
    }

}
